<template>
  <div class="train-wrapper">
    <div class="form-container">
      <div class="rule_title">
        <span class="title-l"> <i class="icon_left"></i>{{ titleTip }} </span>
        <el-link
          @click="handleClickClose"
          class="icon-right"
          icon="el-icon-refresh-left"
          type="primary"
        >
          返回上一页
        </el-link>
      </div>
      <el-form
        label-position="right"
        :model="ruleForm"
        class="infoForm"
        label-width="120px"
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        :disabled="disable"
      >
        <div class="range_tab">基本信息</div>

        <el-row :gutter="24">
          <el-form-item label="试卷名称" prop="paper_name">
            <el-input v-model="ruleForm.paper_name"></el-input>
          </el-form-item>
          <el-form-item label="考试开始时间" prop="exam_start_time">
            <el-date-picker
              v-model="ruleForm.exam_start_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考试结束时间" prop="exam_end_time">
            <el-date-picker
              v-model="ruleForm.exam_end_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="试卷说明" prop="paper_remark">
            <el-input v-model="ruleForm.paper_remark"></el-input>
          </el-form-item>
          <el-form-item label="满分" prop="total_score">
            <el-input
              disabled
              oninput="value=value.replace(/[^\d^\.]/g,'')"
              v-model="ruleForm.total_score"
            ></el-input>
          </el-form-item>
          <el-form-item label="及格分" prop="passing_score">
            <el-input
              oninput="value=value.replace(/[^\d^\.]/g,'')"
              v-model="ruleForm.passing_score"
            ></el-input>
          </el-form-item>
          <el-form-item label="答题时长(min)" prop="duration">
            <el-input
              oninput="value=value.replace(/[^\d^\.]/g,'')"
              v-model="ruleForm.duration"
            ></el-input>
          </el-form-item>
          <el-form-item label="阅卷人" prop="paper_reader_id">
            <el-select v-model="ruleForm.paper_reader_id" filterable clearable>
              <el-option
                v-for="handler in staffData"
                :key="handler.id"
                :label="handler.name"
                :value="handler.id * 1"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="考试范围" prop="exam_range">
            <el-select
              @change="handleChangeRole"
              v-model="ruleForm.exam_range"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in categoryData"
                :key="index"
                :label="item.value"
                :value="item.key * 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="exam_range_ids">
            <el-cascader
              size="mini"
              @change="handleChangeUser"
              v-if="ruleForm.exam_range === 1"
              ref="cascader"
              :options="branchData"
              :show-all-levels="false"
              v-model="ruleForm.exam_range_ids"
              :props="{
                emitPath: false,
                checkStrictly: true,
                label: 'branch_name',
                value: 'id',
                children: 'next_level_data',
                multiple: true,
              }"
              filterable
              clearable
            >
            </el-cascader>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.exam_range === 2"
              multiple
              v-model="ruleForm.exam_range_ids"
              filterable
              clearable
            >
              <el-option
                v-for="item in roleList"
                :label="item.name"
                :value="item.id"
                :key="item.id * 1"
                >{{ item.name }}</el-option
              >
            </el-select>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.exam_range === 3"
              multiple
              v-model="ruleForm.exam_range_ids"
              filterable
              clearable
            >
              <el-option
                v-for="handler in staffData"
                :key="handler.id"
                :label="handler.name"
                :value="handler.id * 1"
              />
            </el-select>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.exam_range === 4"
              multiple
              v-model="ruleForm.exam_range_ids"
              filterable
              clearable
            >
              <el-option
                v-for="item in companyData"
                :label="item.name"
                :value="item.id * 1"
                :key="item.id"
                >{{ item.name }}</el-option
              >
            </el-select>
            <el-select
              @change="handleChangeUser"
              v-if="ruleForm.exam_range === 5"
              multiple
              v-model="ruleForm.exam_range_ids"
              filterable
              clearable
            >
              <el-option
                v-for="item in planData"
                :label="item.name"
                :value="item.id * 1"
                :key="item.id"
                >{{ item.name }}</el-option
              >
            </el-select>
          </el-form-item>
          <!-- <el-popover placement="right" width="200" trigger="click">
            <el-table :data="ruleForm.examination_users" max-height="500">
              <el-table-column width="" property="user_nickname" label="姓名"></el-table-column>
            </el-table>
            <el-button slot="reference" type="text">查看名单</el-button>
          </el-popover> -->
        </el-row>
        <div class="range_tab">考题设置</div>
        <div>
          <div style="padding-bottom: 10px">
            <el-button type="primary" plain size="mini" @click="addQuestion"
              >引入考题</el-button
            >
            <el-button type="primary" plain size="mini" @click="delQuestion"
              >删除考题</el-button
            >
            <div
              v-if="(this.ruleForm.questions || []).length"
              style="float: right; padding-right: 15px; font-size: 15px"
            >
              计总 {{ ruleForm.total_score }}
            </div>
          </div>

          <el-table
            :data="ruleForm.questions"
            class="ques-table"
            @selection-change="handleSelectionChange"
            border
            stripe
            style="margin-bottom: 16px"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              prop=""
              label="序号"
              width="50"
              type="index"
            ></el-table-column>
            <el-table-column prop="question_type" label="题目类型" width="180">
              <template slot-scope="scope">
                {{ QUES_TYPE[scope.row.question_type] }}
              </template>
            </el-table-column>
            <el-table-column prop="question" label="考题" width="">
            </el-table-column>
            <el-table-column prop="question_score" label="分数" width="180">
              <template slot-scope="scope">
                <el-input
                  @input="calcTotalScore"
                  style="width: 140px"
                  v-model="scope.row['question_score']"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
          <el-alert
            v-if="(this.ruleForm.questions || []).length"
            show-icon
            style="margin-top: -11px; margin-bottom: 15px"
            title="拖动题目可进行排序~"
            closable
            type="info"
          >
          </el-alert>
        </div>
        <template>
          <el-form :disabled="disable">
            <div class="range_tab">参加人</div>
            <div style="padding-bottom: 10px">
              <el-popover
                v-if="ruleForm.exam_range in [1, 2, 5]"
                placement="top"
                width="260"
                v-model="addDialogVisible"
              >
                <p style="padding-bottom: 10px">请选择要添加的账号(可多选)</p>
                <el-select multiple v-model="role_ids" filterable clearable>
                  <el-option
                    v-for="handler in staffData"
                    :key="handler.id"
                    :label="handler.name"
                    :value="handler.id * 1"
                  />
                </el-select>
                <div style="text-align: right; margin: 0; padding-top: 10px">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleAccountCancel"
                    >取消</el-button
                  >
                  <el-button type="primary" size="mini" @click="handleAccountOk"
                    >确定</el-button
                  >
                </div>
                <el-button
                  slot="reference"
                  style="margin-right: 10px"
                  type="primary"
                  plain
                  size="mini"
                  >新增</el-button
                >
              </el-popover>
              <el-button type="primary" plain size="mini" @click="handleUserDel"
                >删除</el-button
              >
            </div>
            <el-table
              :max-height="300"
              ref="userTable"
              :data="ruleForm.examination_users"
              @selection-change="handleUserSelectionChange"
              border
              stripe
              style="margin-bottom: 12px"
            >
              <el-table-column :disabled="false" type="selection" width="55">
              </el-table-column>
              <el-table-column
                fixed
                label="序号"
                width="50"
                type="index"
              ></el-table-column>
              <el-table-column prop="user_nickname" label="姓名" width="200">
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.inspection_time ? "已参加" : "未参加" }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="inspection_time"
                label="参加时间"
                width="200"
              >
                <template slot-scope="scope">
                  <div>
                    <span v-time="scope.row.inspection_time"></span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="exam_result" label="结果" width="100">
                <template slot-scope="scope">
                  <div v-if="scope.row.inspection_time">
                    <el-tag
                      :type="
                        ['danger', 'success', 'info'][scope.row.exam_result]
                      "
                    >
                      {{ ["未通过", "通过", "待评分"][scope.row.exam_result] }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="grade" label="得分" width="200">
                <template slot-scope="scope">
                  <div v-if="scope.row.inspection_time">
                    <span
                      v-if="
                        scope.row.exam_result == 0 || scope.row.exam_result == 1
                      "
                    >
                      {{ scope.row.grade }}
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="" label=""> </el-table-column>
            </el-table>
          </el-form>
        </template>
      </el-form>
    </div>
    <div class="operation-footer">
      <div class="footer-wrap">
        <el-button size="small" @click="handleClickClose">关闭</el-button>
        <template v-if="mode !== 'detail'">
          <el-button
            size="small"
            v-show="ruleForm.status !== 1 || mode == 'add'"
            type="primary"
            @click="handleClickSubmit"
            >保存草稿</el-button
          >
          <el-button
            size="small"
            type="primary"
            v-show="mode !== 'add'"
            @click="handleOperation('3')"
            >预览</el-button
          >
          <el-button
            size="small"
            v-show="ruleForm.status === 0 || ruleForm.status === 2"
            type="primary"
            @click="handleOperation('1')"
            >发布试卷</el-button
          >
          <el-button
            size="small"
            v-show="ruleForm.status === 1"
            type="primary"
            @click="handleOperation('2')"
            >关闭考核</el-button
          >
        </template>
      </div>
    </div>
    <!-- <TrainMaterial mode="add" v-if="materialDialogVisible" :dialogVisible="materialDialogVisible"
      @close="handleCloseMaterialDialog"></TrainMaterial> -->
    <QuestionUse
      :checkdQuestions="ruleForm.questions"
      v-if="checkDialogVisible"
      :dialogVisible="checkDialogVisible"
      @ok="checkQuesOk"
      @close="handleCloseCheckDialog"
    ></QuestionUse>
  </div>
</template>
  
<script>
import { AdminBox } from "@/api/customer";
import { organizationBox, roleBox } from "@/api/organization";
import { carrierBox } from "@/api/waybill";
import QuestionUse from "../components/questionUse.vue";
import { timestamp10 } from "@/utils/mUtils";
import {
  ExamPaperCreate,
  ExamPaperUpdate,
  ExamPaperDetail,
  trainingUserOption,
  ExamPaperTookeffect,
  trainingPlanOptions,
  ExamPaperClose,
} from "@/api/qms";
import { QUES_TYPE } from "@/page/qms/constants";
import { commonAddMulty } from "@/utils/mUtils";
import Sortable from "sortablejs"; //引入插件

export default {
  name: "paperpage",
  components: { QuestionUse },
  props: [],
  data() {
    return {
      ruleForm: {
        paper_name: "", // 试卷名
        paper_remark: "", // 试卷说明
        passing_score: "", // 及格分
        paper_reader_id: "", // 阅卷人id
        exam_start_time: "", // 考试开始时间
        exam_end_time: "", // 考试结束时间
        duration: "", // 考试时长:单位-Min
        total_score: "", // 总分数
        exam_range: "", // 考试范围:1-组织，2-角色，3-指定用户，4-承运商，5培训
        exam_range_ids: [], // 考试范围
        questions: [],
        examination_users: [],
      },
      mode: "", // 考题
      rules: {
        paper_name: [
          { required: true, message: "请输入试卷名称", trigger: "blur" },
        ],
        duration: [
          { required: true, message: "请输入答题时长", trigger: "blur" },
        ],
      },
      titleTip: "试卷管理",
      categoryData: [
        {
          key: "1",
          value: "组织",
        },
        {
          key: "2",
          value: "角色",
        },
        {
          key: "4",
          value: "承运商",
        },
        {
          key: "3",
          value: "账号",
        },
        {
          key: "5",
          value: "培训计划",
        },
      ],
      checkDialogVisible: false,
      staffData: [],
      branchData: [],
      roleList: [],
      companyData: [],
      accountData: [],
      planData: [],
      checkedList: [],
      addDialogVisible: false,
      role_ids: [],
      checkedUser: [],
      QUES_TYPE,
    };
  },
  computed: {
    disable() {
      return this.mode === "detail" || this.ruleForm.status === 1;
    },
  },
  watch: {
    $route: {
      handler: function () {
        this.handleChangeMode();
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.handleChangeMode();
    AdminBox({
      user_type: "0",
    }).then((res) => {
      this.staffData = res.data;
    });
    organizationBox({ not_show_first_branch: 1 }).then((res) => {
      this.branchData = res.data;
    });
    roleBox().then((res) => {
      const data = res.data || [];
      this.roleList = data;
    });
    carrierBox().then((res) => {
      this.companyData = res.data;
    });
    trainingPlanOptions({}).then((res) => {
      this.planData = res.data.data;
    });

    // 阻止默认行为
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.rowDrop(); //行拖拽
  },
  methods: {
    handleChangeMode() {
      this.mode = this.$route.query.mode || "add";

      if (this.mode === "add") {
      } else if (this.mode === "detail" || this.mode === "edit") {
        this.getDetail();
      }
    },
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector(
        ".ques-table .el-table__body-wrapper tbody"
      );
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          if (newIndex == oldIndex) return;
          _this.ruleForm.questions.splice(
            newIndex,
            0,
            _this.ruleForm.questions.splice(oldIndex, 1)[0]
          );
          var newArray = _this.ruleForm.questions.slice(0);
          _this.ruleForm.questions = [];
          _this.$nextTick(function () {
            _this.ruleForm.questions = newArray;
          });
        },
      });
    },

    handleAccountOk() {
      // 去重后的id
      const _role_ids = this.role_ids.filter(
        (x) =>
          this.ruleForm.examination_users.findIndex((y) => y.user_id === x) ===
          -1
      );
      this.staffData.forEach((item) => {
        if (_role_ids.includes(item.id)) {
          this.ruleForm.examination_users.push({
            user_id: item.id,
            user_nickname: item.nickname,
          });
        }
      });
      this.handleAccountCancel();
    },
    handleAccountCancel() {
      this.role_ids = [];
      this.addDialogVisible = false;
    },
    handleUserDel() {
      // console.log(this.checkedUser, this.ruleForm.examination_users.filter(item => !this.checkedUser.includes(item.user_id)), 'this.ruleForm.training_user.filter(item=> !this.checkedUser.includes(item.user_id))');
      this.ruleForm.examination_users = this.ruleForm.examination_users.filter(
        (item) => !this.checkedUser.includes(item.user_id)
      );
    },
    handleUserSelectionChange(checked) {
      this.checkedUser = checked.map((item) => item.user_id);
    },
    handleCloseCheckDialog() {
      this.checkDialogVisible = false;
    },
    checkQuesOk(checked) {
      // console.log(checked, 'checkQuesOk');
      this.ruleForm.questions = checked.map((item) => {
        return {
          question_id: item.id,
          question: item.question,
          question_score: item.score,
          question_type: item.question_type,
        };
      });
      this.calcTotalScore();
    },
    calcTotalScore() {
      const scoreArr = this.ruleForm.questions.map(
        (item) => item.question_score
      );
      this.ruleForm.total_score = commonAddMulty(...scoreArr);
      this.ruleForm.passing_score = Math.round(this.ruleForm.total_score * 0.6);
    },
    handleOperation(type) {
      switch (type) {
        case "1":
          if ((this.ruleForm.examination_users || []).length === 0) {
            this.$message({
              message: "请添加参加人",
              type: "warning",
            });
            return;
          }
          ExamPaperTookeffect({
            id: this.ruleForm.id * 1,
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "已发布",
                type: "success",
              });
              this.getDetail();
            }
          });
          break;
        case "2":
          ExamPaperClose({
            id: this.ruleForm.id * 1,
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "已关闭",
                type: "success",
              });
              this.getDetail();
            }
          });
          break;
        case "3":
          this.$router.push({
            name: "exampage",
            query: {
              paperId: this.ruleForm.id,
              mode: "detail",
            },
          });
          // window.open(routeUrl.href, '_blank');
          break;
        default:
          break;
      }
    },
    handleSelectionChange(checked) {
      this.checkedList = checked.map((item) => item.question_id);
    },
    handleClickClose() {
      this.$router.go(-1);
    },
    handleChangeRole() {
      this.ruleForm.exam_range_ids = [];
      this.ruleForm.examination_users = [];
    },
    addQuestion() {
      this.checkDialogVisible = true;
    },
    delQuestion() {
      this.ruleForm.questions = this.ruleForm.questions.filter(
        (item) => !this.checkedList.includes(item.question_id)
      );
      this.calcTotalScore();
    },
    handleChangeUser() {
      if (
        this.ruleForm.exam_range === 1 ||
        this.ruleForm.exam_range === 2 ||
        this.ruleForm.exam_range === 5
      ) {
        let _exam_range = this.ruleForm.exam_range;
        if (_exam_range === 5) {
          _exam_range = 4;
        }
        trainingUserOption({
          range_type: _exam_range, // 1-组织，2-角色 5-培训计划
          range_ids: this.ruleForm.exam_range_ids,
        }).then((res) => {
          let data = res.data.list;
          data = data.map((item) => {
            return {
              user_id: item.id,
              user_nickname: item.nickname,
            };
          });
          this.ruleForm.examination_users = data;
          // console.log(this.ruleForm.examination_users, ' this.ruleForm.examination_users');
        });
      } else if (this.ruleForm.exam_range === 3) {
        const staffs = this.staffData.filter((item) =>
          this.ruleForm.exam_range_ids.includes(item.id)
        );
        this.ruleForm.examination_users = staffs.map((item) => {
          return {
            user_id: item.id,
            user_nickname: item.nickname,
          };
        });
      } else if (this.ruleForm.exam_range === 4) {
        const companys = this.companyData.filter((item) =>
          this.ruleForm.exam_range_ids.includes(item.id)
        );
        this.ruleForm.examination_users = companys.map((item) => {
          return {
            user_id: item.id,
            user_nickname: item.name,
          };
        });
      }
    },
    getDetail() {
      ExamPaperDetail({
        id: this.$route.query.id * 1,
      }).then((res) => {
        const data = res.data.data;
        data.exam_start_time = data.exam_start_time
          ? data.exam_start_time * 1000
          : "";
        data.exam_end_time = data.exam_end_time
          ? data.exam_end_time * 1000
          : "";
        data.exam_range_ids = (data.exam_range_info || []).map(
          (item) => item.range_id
        );
        data.exam_range = data.exam_range === 0 ? "" : data.exam_range;
        data.paper_reader_id =
          data.paper_reader_id === 0 ? "" : data.paper_reader_id;
        this.ruleForm = data;
      });
    },
    handleClickSubmit() {
      if (this.ruleForm.questions.length === 0) {
        this.$message({
          message: "请先添加考题",
          type: "warning",
        });
        return;
      }
      this.ruleForm.questions.forEach((item) => {
        item.question_score = item.question_score * 1;
      });
      const _ruleForm = {
        ...this.ruleForm,
        total_score: this.ruleForm.total_score * 1,
        passing_score: this.ruleForm.passing_score * 1,
        duration: this.ruleForm.duration * 1,
        paper_reader_id: this.ruleForm.paper_reader_id * 1,
        exam_range: this.ruleForm.exam_range * 1,
        exam_start_time: timestamp10(this.ruleForm.exam_start_time) * 1 || 0,
        exam_end_time: timestamp10(this.ruleForm.exam_end_time) * 1 || 0,
      };
      if (this.mode === "add") {
        ExamPaperCreate(_ruleForm).then((res) => {
          if (res.code === 10000) {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.$router.push({
              name: "paperpage",
              query: {
                id: res.data.id,
                mode: "edit",
              },
            });
            // this.getDetail();
          }
        });
      } else {
        ExamPaperUpdate(_ruleForm).then((res) => {
          if (res.code === 10000) {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.getDetail();
          }
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.train-wrapper {
  background: #fff;

  min-height: 100vh;
  box-sizing: border-box;

  .form-container {
    padding: 20px;
  }

  .rule_title {
    // background: red;
    display: flex;
    align-items: center;
    padding-bottom: 18px;
    padding-top: 8px;
    font-size: 14px;
    font-weight: bold;
    justify-content: space-between;

    .title-l {
      display: flex;
      align-items: center;
    }

    .icon_left {
      display: inline-block;
      width: 6px;
      height: 16px;
      background: #f1a357;
      margin-right: 6px;
    }

    .icon-right {
    }
  }

  .range_tab {
    width: 100%;
    height: 30px;
    background: #f2f3f5;
    font-weight: bold;
    line-height: 30px;
    padding-left: 12px;
    margin-bottom: 16px;
    color: #6d6e72;
    font-size: 14px;
    box-sizing: border-box;
  }

  .operation-footer {
    position: fixed;
    width: 100%;
    bottom: 0;
    background: white;
    box-sizing: border-box;
    padding: 15px 0;
    box-shadow: 0px -10px 20px -10px rgba(0, 0, 0, 0.07);
    z-index: 100;

    .footer-wrap {
      width: 86.3%;
      text-align: center;
    }
  }

  .infoForm {
    .el-input {
      width: 200px;
    }

    .el-select,
    .el-cascader {
      width: 200px;
    }
  }
}
</style>